package com.mzj.saas.jobs.config.http;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

@Configuration
public class RestTemplateConfig {

	@Bean(name = "httpClientFactory")
	public SimpleClientHttpRequestFactory simpleClientHttpRequestFactory() {

		SimpleClientHttpRequestFactory facotry = new SimpleClientHttpRequestFactory();
		facotry.setReadTimeout(10000);
		facotry.setConnectTimeout(30000);
		return facotry;
	}

	@Bean(name = "restTemplate")
	public RestTemplate restTemplate(SimpleClientHttpRequestFactory factory,
                                     @Qualifier("restTemplateInterceptor") RestTemplateInterceptor restTemplateInterceptor) {
		RestTemplate restTemplate = new RestTemplate(factory);
		restTemplate.setErrorHandler(new RestTemplateErrorHandler());

		List<ClientHttpRequestInterceptor> rtiList = new ArrayList<ClientHttpRequestInterceptor>();
		rtiList.add(restTemplateInterceptor);
		restTemplate.setInterceptors(rtiList);

		return restTemplate;
	}
}
